const axios = require('axios');
const qs = require('qs');


class API {
    constructor(props) {
        this.config = props || {};
        this.init();
    }
}

API.prototype.xhr = function (method = 'GET', url = '', params = {}, props = {}) {
    // 添加动态参数
    params.timestamp = new Date().getTime();

    let httpDefault = {
        method: method,
        baseURL: this.config.base || '',
        url: url,
        timeout: 20000,
        ...props,
        // `params` 是即将与请求一起发送的 URL 参数
        // `data` 是作为请求主体被发送的数据
        params: method === 'GET' || method === 'DELETE' ? params : null,
        data: method === 'POST' || method === 'PUT' ? qs.stringify(params) : null
    };

    // 通过 Promise 进行回调参数
    return new Promise((resolve, reject) => {
        axios(httpDefault)
            .then((res) => {
                resolve(res);
            })
            .catch((response) => {
                reject(response)
            });
    });
};

API.prototype.init = function (props) {
    let arr = [
        {name : 'get', key : 'GET'},
        {name : 'put', key : 'PUT'},
        {name : 'post', key : 'POST'},
        {name : 'delete', key : 'DELETE'},
    ];
    for (let i=0;i<arr.length;i++){
        this[arr[i].name] = (url = '', data = {}, header = {}, props = {}) =>
            this.xhr(arr[i].key, url, data, header, props);
    }
};

module.exports = {

    ajax : API

};
